package org.springframework.boot.autoconfigure.netty.support;

import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;

import java.lang.annotation.Annotation;
import java.util.Set;

public class RegisterBean {

    /**
     * 动态注册bean
     * @param beanDefinitonRegistry
     * @param beanDefinition
     */
    private static void registerBeanIfNecessary(BeanDefinitionRegistry beanDefinitonRegistry,BeanDefinition beanDefinition){
        //DefaultListableBeanFactory beanDefinitonRegistry = (DefaultListableBeanFactory) app.getAutowireCapableBeanFactory();
        String simpleNameString=beanDefinition.getBeanClassName();
        if(simpleNameString.contains(".")){
            simpleNameString=simpleNameString.substring(simpleNameString.lastIndexOf(".")+1);
        }
        simpleNameString= lowerFirstChar(simpleNameString);

        if(!beanDefinitonRegistry.containsBeanDefinition(simpleNameString)){
            beanDefinitonRegistry.registerBeanDefinition(simpleNameString, beanDefinition);
        }
    }

    private static BeanDefinitionBuilder getBeanDefinitionBuilder(Class clazz){
        return BeanDefinitionBuilder.genericBeanDefinition(clazz);
    }

    private static String lowerFirstChar(String simpleName){
        char[] chars = simpleName.toCharArray();
        chars[0] += 32;
        String res = String.valueOf(chars);
        return res;
    }


    public static void doRegister(BeanDefinitionRegistry beanDefinitonRegistry, String[] arguementResolverBasePackages,Class<? extends Annotation> clazz) {

        Set<Class<?>> classes = ClassScanner.scanPackages(arguementResolverBasePackages, clazz);
            for (Class<?> clzz : classes) {
                registerBeanIfNecessary(beanDefinitonRegistry,getBeanDefinitionBuilder(clzz).getBeanDefinition());
            }
    }
}
